﻿using ET.Monitor.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Data;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Script.Serialization;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WebAPI.App_Code;
using System.Configuration;
using System.Xml;

using System.Web.Helpers;

namespace ET.Monitor.Web.Api
{
    public class PcController : ApiController
    {
        StringHelper sh = new StringHelper();
        string path = ConfigurationManager.ConnectionStrings["xmlUrl"].ConnectionString + "\\WebMenu.xml";

        #region  菜单下载
        [HttpGet]
        public HttpResponseMessage DownloadXml()
        {
            try
            {
                bool isDL = false;
                DataTable dtXml = new DataTable();
                XmlModel xm = new XmlModel("WebMenu");
                dtXml = xm.GetFileXml;
                if (dtXml != null && dtXml.Rows.Count != 0 && dtXml.Rows[0]["B_XML"] != null && dtXml.Rows[0]["B_XML"].ToString() != "")
                {
                    byte[] pics1 = (byte[])dtXml.Rows[0]["B_XML"];
                    FileStream fs = new FileStream(@path, FileMode.Create, FileAccess.Write);
                    BinaryWriter bw = new BinaryWriter(fs);
                    fs.Write(pics1, 0, pics1.Length);
                    fs.Flush();
                    fs.Close();
                    isDL = true;
                }
                object obj = new
                {
                    isDL = isDL
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：DownloadXml");
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }

        #endregion

        #region 登录
        [HttpPost]
        public HttpResponseMessage Login()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象

            string userName = request.Form["name"];
            string password = request.Form["pwd"];
            try
            {
                PersonnelModel pm = new PersonnelModel(userName, password);
                object ck = pm.ObjCheck;
                object obj = new
                {
                    judge = ck.ToString(),
                    uid = userName
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：CheckLogin");
                sh.WriteLog("获取到参数：name=" + userName);
                sh.WriteLog("获取到参数：pwd=" + password);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 菜单

        #region 获取菜单
        [HttpPost]
        public HttpResponseMessage GetAccordionMenu()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象

            string userId = request.Form["uid"];//获取当前用户id

            try
            {
                StringBuilder sb = new StringBuilder();//手风琴字符串
                StringBuilder sbm = new StringBuilder();

                PersonnelModel pm = new PersonnelModel(userId);//实例化用户模型
                string _name = pm.UserName;
                string roleId = pm.Group;//获取到该用户的角色id
                DataTable dt = new DataTable();
                dt = GetTreeList();//获取到菜单
                                   /*按照order进行排序，生成新的dtCopy*/
                DataTable dtCopy = dt.Copy();
                DataView dv = dt.DefaultView;
                dv.Sort = "order";
                dtCopy = dv.ToTable();
                /*******************/
                DataRow[] dr = null;
                DataRow[] dr_HomePage = null;
                dr_HomePage = dtCopy.Select("PID='000'");//菜单第一行默认为登录后的默认显示页面
                string HomePageUrl = dr_HomePage[0][6].ToString();//默认界面的路径
                string HomePageCn = dr_HomePage[0][1].ToString();//默认界面的中文名
                dr = dtCopy.Select("PID='00'");
                int[] ChildMenuSeries = new int[dr.Length];//子菜单的深度
                string RootMenuId = "";//一级菜单的Id
                int c = dr.Length;

                sb.AppendFormat("<ul class=\"mtree\" id=\"ul_RootMenu\">");
                for (int i = 0; i < dr.Length; i++)
                {
                    string[] nodeRoleId = dr[i][5].ToString().TrimStart(',').TrimEnd(',').Split(',');
                    string visible = dr[i][4].ToString();
                    if (nodeRoleId.Contains(roleId) && visible == "1")
                    {
                        DataRow[] _dr = dtCopy.Select("PID='00'");
                        if (_dr.Length > 0)
                        {
                            RootMenuId = RootMenuId + dr[i][0].ToString() + ",";
                            sb.AppendFormat("<li><a _href='{1}' href='javascript: void(0)'>{0}</a>", dr[i][1], dr[i][6]);
                            GetMenuUlli(dtCopy, roleId, dr[i][0].ToString(), sb);
                            sb.Append("</li>");
                        }
                    }
                }
                sb.AppendFormat("</ul>");
                dt = new DataTable();
                dtCopy = new DataTable();
                RootMenuId = RootMenuId.Substring(0, RootMenuId.Length - 1);
                object obj = new
                {
                    tabPage = sb.ToString(),
                    rootMenuId = RootMenuId,
                    number = c.ToString(),
                    FRootMenu = HomePageUrl,
                    HomePageCn = HomePageCn,
                    uname = _name
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetAccordionMenu");
                sh.WriteLog("获取到参数：uid=" + userId);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion 

        #region 菜单拼接
        private void GetMenuUlli(DataTable dt, string roleId, string id, StringBuilder sb)
        {
            if (dt != null)
            {
                DataRow[] _dr = dt.Select("PID='" + id + "'");
                if (_dr.Length > 0)
                {
                    sb.AppendFormat("<ul>");
                    for (int i = 0; i < _dr.Length; i++)
                    {
                        string[] nodeRoleId = _dr[i][5].ToString().TrimStart(',').TrimEnd(',').Split(',');
                        if (nodeRoleId.Contains(roleId) && _dr[i][4].ToString() == "1")
                        {
                            sb.AppendFormat("<li><a _href='" + _dr[i][6] + "' href='javascript: void(0)'>" + _dr[i][1] + "</a>");
                            GetMenuUlli(dt, roleId, _dr[i][0].ToString(), sb);
                            sb.Append("</li>");
                        }
                    }
                    sb.AppendFormat("</ul>");
                }
            }
        }
        #endregion

        #region 获取菜单树

        /// <summary>
        /// 获取 DatTable Tree
        /// </summary>
        private DataTable GetTreeList()
        {
            //否则写全命名空间：System.Web.HttpContext.Current.Server.MapPath();
            //注意：如果是在一个类库下的一个类中、要先添加引入using System.Web; 因为新建一个类库时默认是不引入using System.Web的!
            DataTable dt = new DataTable();
            XmlTextReader reader = new XmlTextReader(path);

            reader.WhitespaceHandling = WhitespaceHandling.None;
            XmlDocument xmlDoc = new XmlDocument();
            //将文件加载到XmlDocument对象中
            xmlDoc.Load(reader);

            //关闭连接
            reader.Close();

            XmlNode xnod = xmlDoc.DocumentElement;

            if (!dt.Columns.Contains("ID"))
                dt.Columns.Add("ID");
            if (!dt.Columns.Contains("NAME"))
                dt.Columns.Add("NAME");
            if (!dt.Columns.Contains("PID"))
                dt.Columns.Add("PID");
            if (!dt.Columns.Contains("ORDER"))
                dt.Columns.Add("ORDER");
            if (!dt.Columns.Contains("VISIBLE"))
                dt.Columns.Add("VISIBLE");
            if (!dt.Columns.Contains("OWER"))
                dt.Columns.Add("OWER");
            if (!dt.Columns.Contains("FILNAME"))
                dt.Columns.Add("FILNAME");
            if (!dt.Columns.Contains("IMG"))
                dt.Columns.Add("IMG");
            if (!dt.Columns.Contains("TYPE"))
                dt.Columns.Add("TYPE");
            if (!dt.Columns.Contains("English"))
                dt.Columns.Add("English");
            if (!dt.Columns.Contains("German"))
                dt.Columns.Add("German");
            if (!dt.Columns.Contains("Japanese"))
                dt.Columns.Add("Japanese");
            XmlToDataTable(xnod, dt);
            return dt;
        }
        #endregion

        #region 将XML转换成 DataTable
        /// <summary>
        /// 将XML转换成 DataTable
        /// </summary>
        /// <param name="xnod"></param>
        /// <param name="intLevel"></param>
        private void XmlToDataTable(XmlNode xnod, DataTable dt)
        {
            DataRow dr = dt.NewRow();
            XmlNode xnodWorking;

            //如果是元素节点，获取它的属性
            if (xnod.NodeType == XmlNodeType.Element)
            {
                XmlNamedNodeMap mapAttributes = xnod.Attributes;
                if (mapAttributes.Count > 0)
                {
                    dr[0] = mapAttributes.Item(0).Value;
                    dr[1] = mapAttributes.Item(1).Value;
                    dr[2] = mapAttributes.Item(2).Value;
                    dr[3] = mapAttributes.Item(3).Value;
                    dr[4] = mapAttributes.Item(4).Value;
                    dr[5] = mapAttributes.Item(5).Value;
                    dr[6] = mapAttributes.Item(6).Value;
                    dr[7] = mapAttributes.Item(7).Value;
                    dr[8] = mapAttributes.Item(8).Value;
                    dr[9] = mapAttributes.Item(9).Value;
                    dr[10] = mapAttributes.Item(10).Value;
                    dr[11] = mapAttributes.Item(11).Value;
                    dt.Rows.Add(dr);
                }

                //如果还有子节点，就递归地调用这个程序
                if (xnod.HasChildNodes)
                {
                    xnodWorking = xnod.FirstChild;
                    while (xnodWorking != null)
                    {
                        XmlToDataTable(xnodWorking, dt);
                        xnodWorking = xnodWorking.NextSibling;
                    }
                }
            }
        }
        #endregion

        #endregion

        #region  实时监控

        #region 获取故障信息
        [HttpPost]
        public HttpResponseMessage GetFaultInfo()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string userid = request.Form["uid"];
            int pageSize = Convert.ToInt32(request.Form["pageSize"]);
            int pageIndex = Convert.ToInt32(request.Form["pageIndex"]);

            try
            {
                OrgModel om = new OrgModel(userid);
                DataTable dtAllOrg = new DataTable();
                dtAllOrg = om.DtUserStation;                    //用户与电站关系

                string[] arr = dtAllOrg.AsEnumerable().Select(x => x["T_ORGID"].ToString()).ToArray();

                string strStationId = "'" + string.Join("','", arr) + "'";

                int intPageSize = 10, intPageIndex = 1, totalPage = 0;
                intPageSize = pageSize;     //页面数据数量
                intPageIndex = pageIndex;   //页面索引
                int totalCount = 0;
                StationModel sm = new StationModel(strStationId, intPageSize, intPageIndex);
                totalCount = sm.RealFaultCount;
                if (totalCount != 0 && totalCount % intPageSize == 0)
                    totalPage = totalCount / intPageSize;
                else
                    totalPage = totalCount / intPageSize + 1;
                DataTable dtModel = sm.RealFaultDt;
                StringBuilder sb = new StringBuilder();
                if (dtModel != null && dtModel.Rows.Count > 0)
                {
                    dtModel.Columns.Add("id", typeof(string));
                    if (dtModel.Rows.Count > 0)
                    {
                        //DataTable dtPage = dtModel.AsEnumerable().Skip((intPageIndex - 1) * intPageSize).Take(intPageSize).CopyToDataTable();
                        sb.Append("<table id=\"tb_list_body\" style=\"width:100%;height:100%;border:0px;\" cellpadding=\"0\" cellspacing=\"0\">");
                        for (int i = 0; i < dtModel.Rows.Count; i++)
                        {
                            if (i == 0 || i % 2 == 0)
                            {
                                sb.Append("<tr class=\"gz_tr_2_1\">");
                            }
                            else
                            {
                                sb.Append("<tr class=\"gz_tr_2_2\">");
                            }

                            sb.Append("<td width=\"10%\" class=\"gz_td_2_1_l\">" + (i + 1).ToString() + "</td>");
                            sb.Append("<td width=\"15%\" class=\"gz_td_2_1_c\">" + dtModel.Rows[i]["T_PLANTDESC"].ToString() + "</td>");
                            sb.Append("<td width=\"15%\" class=\"gz_td_2_1_c\">" + dtModel.Rows[i]["T_UNITDESC_CN"].ToString() + "</td>");
                            sb.Append("<td width=\"15%\" class=\"gz_td_2_1_c\">" + dtModel.Rows[i]["T_TYPEDESC"].ToString() + "</td>");
                            sb.Append("<td width=\"15%\" class=\"gz_td_2_1_c\">" + dtModel.Rows[i]["T_FAULTDESC_CN"].ToString() + "</td>");
                            sb.Append("<td width=\"30%\" class=\"gz_td_2_1_r\">" + dtModel.Rows[i]["T_STARTTIME"].ToString() + "</td>");
                            sb.Append("</tr>");
                        }
                        sb.Append("</table>");
                    }
                }
                object obj = new
                {
                    table = sb.ToString(),
                    total = totalPage

                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetFaultInfo");
                sh.WriteLog("获取到参数：uid=" + userid);
                sh.WriteLog("获取到参数：pageSize=" + pageSize);
                sh.WriteLog("获取到参数：pageIndex=" + pageIndex);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 获取故障数量
        [HttpPost]
        public HttpResponseMessage GetFaultCount()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string userid = request.Form["uid"];

            try
            {
                OrgModel om = new OrgModel(userid);
                DataTable dtAllOrg = new DataTable();
                dtAllOrg = om.DtUserStation;                    //用户与电站关系

                string[] arr = dtAllOrg.AsEnumerable().Select(x => x["T_ORGID"].ToString()).ToArray();

                string strStationId = "'" + string.Join("','", arr) + "'";

                StationModel sm = new StationModel(strStationId, 0, 0);
                int dtModel = 0;
                dtModel = sm.RealFaultCount;
                object obj = new
                {
                    faultcount = dtModel
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetFaultCount");
                sh.WriteLog("获取到参数：uid=" + userid);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 获取集团数据

        #region 集团参数
        [HttpPost]
        public HttpResponseMessage LoadGroup()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string userid = request.Form["uid"];
            string id = request.Form["id"];
            try
            {
                CliqueModel cm = new CliqueModel(id);
                StationModel sm = new StationModel("'" + id + "'", "负荷,电量".Split(','));

                List<double[]> lt_powerdl = sm.RealVal;


                double jt_rl = cm.SumRL;

                double d_ljdl = cm.DlSumDL;
                double jt_gl = lt_powerdl[0][0];
                string jtgl = "", jtdl = "";
                jtgl = Math.Round(jt_gl, 2).ToString();

                double jt_dl = lt_powerdl[1][0];

                jtdl = Math.Round(jt_dl, 2).ToString();

                string _group = "{rl:'" + jt_rl + "',gl:'" + jtgl + "',rdl:'" + jtdl + "'";

                cm = new CliqueModel(DateTime.Parse(DateTime.Now.Year + "-01-01"), Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59")).AddDays(-1));

                double d_ndl = cm.YearDL + jt_dl;
                if (DateTime.Now.Day == 1 && DateTime.Now.Month == 1) d_ndl = jt_dl;

                double d_bml = Math.Round(d_ljdl / 1000 * 0.36);

                _group += ",ndl:" + d_ndl + ",jym:" + d_bml + ",ljfd:" + d_ljdl + "}";
                _group = "[" + _group + "]";

                object obj = new
                {
                    corporation = _group
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetFaultCount");
                sh.WriteLog("获取到参数：uid=" + userid);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 电站参数
        string tree = "";
        private static DataTable dtZtree = new DataTable();

        string _station = "", _city = "", _province = "";
        double z_rl = 0, z_gl = 0;
        [HttpPost]
        public HttpResponseMessage LoadAllCityMap()
        {

            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string userid = request.Form["uid"];
            try
            {
                OrgModel om = new OrgModel(userid);
                DataTable dtStation = om.AllOrgStationInfo;          //所有用户电站       
                DataTable dtCity = om.DtCity;
                string[] arr = dtStation.AsEnumerable().Select(x => x["T_ORGID"].ToString()).ToArray();

                StationModel sm = new StationModel("'" + string.Join("','", arr) + "'");
                DataTable dt_rl = sm.AllRL;

                sm = new StationModel("'" + string.Join("','", arr) + "'", "负荷,电量,状态".Split(','));

                List<double[]> lt_powerdl = sm.RealVal;

                double[] d_dl = lt_powerdl[1];
                double[] d_Powre = lt_powerdl[0];
                double[] d_State = lt_powerdl[2];

                double _dl = 0;
                double _rl = 0, _gl = 0;
                int ar_num = 0;
                int _state = 0;

                List<double[]> l_stationinfo = new List<double[]>();


                DataTable dt_station = new DataTable(); //新建一个DataTable的实例dt
                dt_station.Columns.Add(new DataColumn("T_ORGID", typeof(string)));
                dt_station.Columns.Add(new DataColumn("T_CITYID", typeof(string)));
                dt_station.Columns.Add(new DataColumn("D_RL", typeof(string)));
                dt_station.Columns.Add(new DataColumn("D_DL", typeof(string)));
                dt_station.Columns.Add(new DataColumn("D_GL", typeof(string)));
                dt_station.Columns.Add(new DataColumn("I_STATE", typeof(string)));
                DataRow dr_station; //用DataTable的NewRow方法新建一个DataRow对象的实例dr
                foreach (DataRow dr in dtStation.Rows)
                {
                    dr_station = dt_station.NewRow();

                    sm = new StationModel(dr["T_ORGID"].ToString());
                    tree += "{id:'" + dr["T_ORGID"] + "',pId:'" + dr["T_CITYID"] + "',nodeID:'" + dr["T_ORGID"] + "',name:'" + dr["T_PLANTDESC"] + "',t:'" + dr["T_PLANTDESC"] + "',grade:'3',LONG:'" + dr["D_LONG"] + "',LAT:'" + dr["D_LAT"] + "'},";
                    dr_station[0] = dr["T_ORGID"];
                    dr_station[1] = dr["T_CITYID"];
                    #region   计算
                    ar_num = Array.IndexOf(arr, dr["T_ORGID"].ToString());

                    DataRow[] dr_rl = dt_rl.Select("T_ORGID ='" + dr["T_ORGID"].ToString() + "'", "t_time desc");
                    if (dr_rl != null && dr_rl.Length > 0)
                    {
                        _rl = Convert.ToDouble(dr_rl[0][3].ToString());
                        dr_station[2] = _rl;
                        _rl = Math.Round(_rl, 2);

                    }

                    _gl = 0;
                    if (d_Powre[ar_num] != -99999 && d_Powre[ar_num].ToString() != "非数字")
                    {
                        _gl = Math.Round(d_Powre[ar_num], 2);

                        dr_station[4] = d_Powre[ar_num];
                    }

                    _dl = 0;
                    if (d_dl[ar_num] != -99999 && d_dl[ar_num].ToString() != "非数字")
                    {
                        _dl = Math.Round(d_dl[ar_num], 2);//电量[ar_num];

                        dr_station[3] = d_dl[ar_num];
                    }

                    _state = 0;
                    if (d_State[ar_num].ToString() != "非数字" && d_State[ar_num] != -99999)
                    {
                        _state = Convert.ToInt32(d_State[ar_num]);
                        dr_station[5] = _state;
                    }
                    double _cl = Math.Round((_gl / _rl) * 100, 2);
                    if (_gl == 0 || _rl == 0)
                    {
                        _cl = 0;
                    }

                    _rl = Math.Round(_rl, 2);
                    _gl = Math.Round(_gl, 2);
                    _dl = Math.Round(_dl, 2);

                    dt_station.Rows.Add(dr_station); //把这一行插入到到表格dt中

                    #endregion
                    _station += "{ID:'" + dr["T_ORGID"] + "',NAME:'" + dr["T_PLANTDESC"] + "',LONG:'" + dr["D_LONG"] + "',LAT:'" + dr["D_LAT"] + "',status:'" + _state + "',";

                    _station += "rl:'" + _rl + "',"; _station += "gl:'" + _gl + "',"; _station += "rf:'" + _dl + "',";
                    _station += "cl:'" + _cl + "',"; _station += "date:'" + dr["D_STARTDATE"] + "'},";
                }

                string strPrivinceID = "";
                string _cityid = "('" + string.Join("','", dtStation.AsEnumerable().Select(x => x["T_CITYID"].ToString()).ToArray()) + "')";   //省ID
                DataRow[] drCity = dtCity.Select("T_CITYID in " + _cityid, "T_PARENTID asc");
                int i_dzs = 0;

                DataTable dt_city = new DataTable(); //新建一个DataTable的实例dt
                dt_city.Columns.Add(new DataColumn("T_CITYID", typeof(string)));
                dt_city.Columns.Add(new DataColumn("T_PARENTID", typeof(string)));
                dt_city.Columns.Add(new DataColumn("D_RL", typeof(string)));
                dt_city.Columns.Add(new DataColumn("D_GL", typeof(string)));
                dt_city.Columns.Add(new DataColumn("I_STATE", typeof(int)));
                dt_city.Columns.Add(new DataColumn("I_CHILD", typeof(int)));
                DataRow dr_ncity; //用DataTable的NewRow方法新建一个DataRow对象的实例dr

                int i_state = 3;
                foreach (DataRow dr in drCity)
                {
                    dr_ncity = dt_city.NewRow();
                    i_dzs = 0;
                    tree += "{id:'" + dr["T_CITYID"] + "',pId:'" + dr["T_PARENTID"] + "',nodeID:'" + dr["T_CITYID"] + "',name:'" + dr["T_CITYDESC"] + "',t:'" + dr["T_CITYDESC"] + "',grade:'2',LONG:'" + dr["D_LONG"] + "',LAT:'" + dr["D_LAT"] + "'},";

                    strPrivinceID += "'" + dr["T_PARENTID"] + "',";
                    dr_ncity[0] = dr["T_CITYID"].ToString();
                    dr_ncity[1] = dr["T_PARENTID"].ToString();
                    DataRow[] dr_city = dt_station.Select("T_CITYID = '" + dr["T_CITYID"].ToString() + "'");
                    i_dzs = dr_city.Length;
                    z_rl = 0;
                    z_gl = 0;
                    i_state = 3;
                    dr_ncity[5] = i_dzs;
                    for (int j = 0; j < dr_city.Length; j++)
                    {
                        z_rl += Convert.ToDouble(dr_city[j]["D_RL"].ToString());
                        z_gl += Convert.ToDouble(dr_city[j]["D_GL"].ToString());
                        if (i_state > Convert.ToInt32(dr_city[j]["I_STATE"].ToString())) i_state = Convert.ToInt32(dr_city[j]["I_STATE"].ToString());
                    }
                    dr_ncity[4] = i_state;
                    dr_ncity[2] = z_rl;
                    dr_ncity[3] = z_gl; _rl = Math.Round(z_rl, 2);
                    _gl = Math.Round(z_gl, 2);

                    _city += "{ID:'" + dr["T_CITYID"] + "',NAME:'" + dr["T_CITYDESC"] + "',LONG:'" + dr["D_LONG"] + "',LAT:'" + dr["D_LAT"] + "',status:'" + i_state + "',";
                    _city += "rl:'" + _rl + "',";
                    _city += "gl:'" + _gl + "',children:'" + i_dzs + "'},";
                    dt_city.Rows.Add(dr_ncity); //把这一行插入到到表格dt中
                }

                strPrivinceID = "(" + strPrivinceID.Substring(0, strPrivinceID.Length - 1) + ")";   //省ID
                DataRow[] drPrivince = dtCity.Select("T_CITYID in " + strPrivinceID);


                double jt_he = 0;
                foreach (DataRow dr in drPrivince)
                {
                    tree += "{id:'" + dr["T_CITYID"] + "',pId:'" + dr["T_PARENTID"] + "',nodeID:'" + dr["T_CITYID"] + "',name:'" + dr["T_CITYDESC"] + "',t:'" + dr["T_CITYDESC"] + "',grade:'1',LONG:'" + dr["D_LONG"] + "',LAT:'" + dr["D_LAT"] + "'},";

                    DataRow[] dr_city = dt_city.Select("T_PARENTID = '" + dr["T_CITYID"].ToString() + "'");
                    z_rl = 0;
                    z_gl = 0;
                    i_dzs = 0;
                    for (int j = 0; j < dr_city.Length; j++)
                    {
                        z_rl += Convert.ToDouble(dr_city[j]["D_RL"].ToString());
                        z_gl += Convert.ToDouble(dr_city[j]["D_GL"].ToString());
                        if (i_state > Convert.ToInt32(dr_city[j]["I_STATE"].ToString())) i_state = Convert.ToInt32(dr_city[j]["I_STATE"].ToString());
                        i_dzs += Convert.ToInt32(dr_city[j]["I_CHILD"].ToString());
                    }
                    try
                    {
                        i_state = dr_city.Min(r => r.Field<int>("I_STATE"));
                    }
                    catch
                    {
                        i_state = 3;
                    }
                    _rl = Math.Round(z_rl, 2);
                    _gl = Math.Round(_gl, 2);

                    _province += "{ID:'" + dr["T_CITYID"] + "',NAME:'" + dr["T_CITYDESC"] + "',LONG:'" + dr["D_LONG"] + "',LAT:'" + dr["D_LAT"] + "',rl:'" + _rl + "',gl:'" + _gl + "',status:'" + i_state + "',children:'" + i_dzs + "'},";
                }

                CliqueModel cm = new CliqueModel(DateTime.Now.Date, DateTime.Now);

                if (tree != "")
                    tree = "[" + tree.Substring(0, tree.Length - 1) + "]";

                if (_city != "")
                    _city = "[" + _city.Substring(0, _city.Length - 1) + "]";
                if (_station != "")
                    _station = "[" + _station.Substring(0, _station.Length - 1) + "]";
                if (_province != "")
                    _province = "[" + _province.Substring(0, _province.Length - 1) + "]";

                object obj = new
                {
                    station = _station,
                    city = _city,
                    province = _province,
                    tree = tree,
                    jt_he = jt_he
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：LoadAllCityMap");
                sh.WriteLog("获取到参数：uid=" + userid);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #endregion

        #region 电站数据

        #region 电站监控数据
        [HttpPost]
        public HttpResponseMessage GetMonitorInfo()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string dzid = request.Form["sid"];                      //电站编号
            int second = Convert.ToInt32(request.Form["second"]);   //间隔时间
            try
            {
                DateTime st = DateTime.Now;
                StationModel ms = new StationModel(dzid);

                OrgModel or = new OrgModel(dzid);
                List<string> orginfo = or.GroupInfo;
                string orgS = orginfo[0];
                string orgC = orginfo[1];
                string sname = orginfo[2];
                DateTime et = DateTime.Now;
                double num = (et - st).TotalMilliseconds;
                st = DateTime.Now;

                string sm_split = "负荷,电量,累计电量,辐照度";

                StationModel sm = new StationModel("'" + dzid + "'", sm_split.Split(','));
                List<double[]> lt_powerdl = sm.RealVal;

                double rf = 0;
                rf = Math.Round(lt_powerdl[1][0], 2);

                double yf = new StationModel(dzid, Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-1 0:00:00")), Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59")).AddDays(-1)).DL + rf;
                if (DateTime.Now.Day == 1) yf = rf;

                double nf = new StationModel(dzid, Convert.ToDateTime(DateTime.Now.ToString("yyyy-1-1 0:00:00")), Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59")).AddDays(-1)).DL + rf;
                if (DateTime.Now.Day == 1 && DateTime.Now.Month == 1) nf = rf;

                double ljf = 0;

                ljf = Math.Round(lt_powerdl[2][0], 2);

                double rl = ms.RL;

                double ssfh = 0;

                ssfh = Math.Round(lt_powerdl[0][0], 2);

                double nbjsl = ms.InverterCount;

                double fzd = 0;
                fzd = Math.Round(lt_powerdl[3][0], 2);

                double jpco2 = Math.Round(fix(ljf / 10000 * 0.997), 2);
                double jym = Math.Round(fix(ljf / 10000 * 0.36), 2);


                double[] _line = new StationModel(dzid, DateTime.Today, DateTime.Now, second).Line;
                double[] line = new double[_line.Length + 1];
                if (_line != null)
                {
                    for (int i = 0; i < _line.Length; i++)
                    {
                        if (double.IsNaN(_line[i]))
                            line[i + 1] = 0;
                        else
                            line[i + 1] = Math.Round(_line[i], 2);
                    }
                }
                DateTime dts = DateTime.Now;
                DateTime dte = new DateTime(DateTime.Now.Year, 1, 1);
                DataTable dtday = new StationModel(dzid, dte, dts).DtTotalMonthDL;

                double[] dlchart = new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
                for (int i = 0; i < dtday.Rows.Count; i++)
                {
                    if (Convert.ToInt32(dtday.Rows[i]["月"]) == Convert.ToInt32(DateTime.Now.Month))
                    {
                        if (DateTime.Now.Day == 1) dlchart[Convert.ToInt32(dtday.Rows[i]["月"]) - 1] = Math.Round(lt_powerdl[1][0], 2);
                        else dlchart[Convert.ToInt32(dtday.Rows[i]["月"]) - 1] = Math.Round(Convert.ToDouble(dtday.Rows[i]["合计"]) + lt_powerdl[1][0], 2);
                    }
                    else
                        dlchart[Convert.ToInt32(dtday.Rows[i]["月"]) - 1] = Math.Round(Convert.ToDouble(dtday.Rows[i]["合计"]), 2);
                }

                object obj = new
                {
                    sname = sname,
                    orgS = orgS,
                    orgC = orgC,
                    rf = Math.Round(rf, 2),
                    yf = Math.Round(yf, 2),
                    nf = Math.Round(nf, 2),
                    ljf = ljf,
                    rl = rl,
                    ssfh = ssfh,
                    nbjsl = nbjsl,
                    fzd = fzd,
                    jpco2 = jpco2,
                    jym = jym,
                    line = line,
                    dlchart = dlchart
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetMonitorInfo");
                sh.WriteLog("获取到参数：uid=" + dzid);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        private double fix(object obj)
        {
            if (obj == null)
            {
                return 0;
            }
            else if (double.IsNaN((double)obj))
            {
                return 0;
            }
            else
            {
                return (double)obj;
            }

        }
        [HttpPost]
        public HttpResponseMessage GetMonitorInfoChart()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string sid = request.Form["sid"];                      //电站编号
            try
            {
                string sm_split = "电量";

                StationModel sm = new StationModel("'" + sid + "'", sm_split.Split(','));
                List<double[]> lt_powerdl = sm.RealVal;

                double[] _line = new StationModel(sid, DateTime.Today, DateTime.Now, 360).Line;
                double[] line = new double[_line.Length + 1];
                if (_line != null)
                {
                    for (int i = 0; i < _line.Length; i++)
                    {
                        if (double.IsNaN(_line[i]))
                            line[i + 1] = 0;
                        else
                            line[i + 1] = Math.Round(_line[i], 2);
                    }
                }
                DateTime dts = DateTime.Now;
                DateTime dte = new DateTime(DateTime.Now.Year, 1, 1);
                DataTable dtday = new StationModel(sid, dte, dts).DtTotalMonthDL;

                double[] dlchart = new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
                for (int i = 0; i < dtday.Rows.Count; i++)
                {
                    if (Convert.ToInt32(dtday.Rows[i]["月"]) == Convert.ToInt32(DateTime.Now.Month))
                    {
                        if (DateTime.Now.Day == 1)
                        {
                            dlchart[Convert.ToInt32(dtday.Rows[i]["月"]) - 1] = Math.Round(lt_powerdl[0][0], 2);
                        }
                        else
                        {
                            dlchart[Convert.ToInt32(dtday.Rows[i]["月"]) - 1] = Math.Round(Convert.ToDouble(dtday.Rows[i]["合计"]) + lt_powerdl[0][0], 2);
                        }
                    }
                    else
                    {
                        dlchart[Convert.ToInt32(dtday.Rows[i]["月"]) - 1] = Math.Round(Convert.ToDouble(dtday.Rows[i]["合计"]), 2);

                    }
                }
                object obj = new
                {
                    line = line,
                    dlchart = dlchart
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetMonitorInfoChart");
                sh.WriteLog("获取到参数：uid=" + sid);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 逆变器一览
        [HttpPost]
        public HttpResponseMessage GetPlantFaultList()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string stationId = request.Form["stationId"];                      //电站编号
            try
            {
                StringBuilder sb = new StringBuilder();
                StationModel sm = new StationModel(stationId);
                DataTable dt = sm.DtFaultDetailInfo;
                if (dt != null && dt.Rows.Count > 0)
                {

                    sb.Append("<table id=\"tb_fault\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\" border='0'>");
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        sb.Append("<tr class=\"tr_2\">");
                        sb.AppendFormat("<td width=\"10%\" class='td_2_l' valign='middle' align='center'>{0}</td>", i + 1); ;

                        sb.AppendFormat("<td width=\"20%\" class='td_2_c' valign='middle' align='center'>{0}</td>", dt.Rows[i]["T_FAULTDESC_CN"].ToString());
                        sb.AppendFormat("<td width=\"20%\" class='td_2_c' valign='middle'  align='center'>{0}</td>", dt.Rows[i]["T_FAULTRECORD_CN"].ToString());

                        DateTime startTime = DateTime.Parse(dt.Rows[i]["T_STARTTIME"].ToString());
                        TimeSpan ts = DateTime.Now - startTime;
                        string dateFormat = "{0}天 {1}时 {2}分 {3}秒";
                        sb.AppendFormat("<td width=\"25%\" class='td_2_c' valign='middle'  align='center'>{0}</td>", startTime.ToString("yyyy/MM/dd HH:mm:ss"));
                        sb.AppendFormat("<td width=\"25%\" class='td_2_r' valign='middle'  align='center'>{0}</td>", string.Format(dateFormat, ts.Days, ts.Hours, ts.Minutes, ts.Seconds));
                        sb.Append("</tr>");
                    }
                    sb.Append("</table>");
                }
                object obj = new
                {
                    fault = sb.ToString()

                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetPlantFaultList");
                sh.WriteLog("获取到参数：uid=" + stationId);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 逆变器详细信息
        [HttpPost]
        public HttpResponseMessage InverterLoad()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string iid = request.Form["id"];
            try
            {
                InverterModel im = new InverterModel(iid);
                StringBuilder sb_l = new StringBuilder();
                StringBuilder sb_r = new StringBuilder();
                DataTable dt = im.DtInverterInfo;
                string inverterName = "";
                if (dt != null && dt.Rows.Count > 0)
                {
                    inverterName = dt.Rows[0]["T_UNITDESC_CN"].ToString();
                }

                ArrayList list = im.ListInverter;
                if (list.Count != 0)
                {
                    string _dlVal = "";
                    string[] columnName = (string[])list[0];
                    string[] points = (string[])list[1];
                    PointModel pm = new PointModel(points);
                    double[] dlVal = (double[])pm.RealValArray;
                    int half = columnName.Length / 2;
                    sb_l.Append("<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">");
                    for (int i = 0; i < half; i++)
                    {
                        if (dlVal[i] == -99999)
                        {
                            //dlVal[i] = 0;
                            _dlVal = "未取到";
                        }
                        else
                        {
                            _dlVal = Math.Round(Convert.ToDouble(dlVal[i]), 2).ToString();
                            dlVal[i] = Math.Round(Convert.ToDouble(dlVal[i]), 2);
                        }
                        if (i == 0)
                        {
                            sb_l.Append("<tr class=\"tr_1\"><td class=\"td_1_l\" width=\"50%\">" + columnName[i] + "</td>");
                            sb_l.Append("<td class=\"td_1_r\" width=\"50%\">" + _dlVal + "</td>");
                        }
                        else
                        {
                            sb_l.Append("<tr class=\"tr_1\" ><td class=\"td_2_l\" width=\"50%\">" + columnName[i] + "</td>");
                            sb_l.Append("<td class=\"td_2_r\" width=\"50%\">" + _dlVal + "</td>");
                        }
                    }
                    sb_l.Append("</table>");

                    sb_r.Append("<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">");
                    for (int i = half; i < columnName.Length; i++)
                    {
                        if (dlVal[i] == -99999)
                        {
                            dlVal[i] = 0;
                            _dlVal = "未取到";
                        }
                        else
                        {
                            dlVal[i] = Math.Round(Convert.ToDouble(dlVal[i]), 2);
                            _dlVal = Math.Round(Convert.ToDouble(dlVal[i]), 2).ToString();
                        }
                        if (i == 0)
                        {
                            sb_r.Append("<tr class=\"tr_1\"><td class=\"td_1_l\" width=\"50%\">" + columnName[i] + "</td>");
                            sb_r.Append("<td class=\"td_1_r\" width=\"50%\">" + _dlVal + "</td>");
                        }
                        else
                        {
                            sb_r.Append("<tr class=\"tr_1\" ><td class=\"td_2_l\" width=\"50%\">" + columnName[i] + "</td>");
                            sb_r.Append("<td class=\"td_2_r\" width=\"50%\">" + _dlVal + "</td>");
                        }
                    }
                    sb_r.Append("</table>");
                }
                object obj = new
                {
                    name = inverterName,
                    tb_l = sb_l.ToString(),
                    tb_r = sb_r.ToString(),
                    val = 0
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetPlantFaultList");
                sh.WriteLog("获取到参数：uid=" + iid);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }

        #endregion

        #endregion

        #endregion

        #region 性能优化

        #region 逆变器对比      

        #region 逆变器对比
        [HttpPost]
        public HttpResponseMessage SaveChart()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string cParaId = request.Form["id"];
            string desc = request.Form["name"];
            try
            {
                OtherModel om = new OtherModel();
                int count = om.ChartCount;
                count += 1;
                string cType = "bar";
                string cId = "chart-" + count;
                string cModelName = "InverterModel";
                string cAttribute = "Elect";
                om = new OtherModel(cId, cType, desc, cModelName, cAttribute, cParaId);
                bool judge = om.AddChartModel;

                object obj = new
                {
                    res = judge
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：SaveChart");
                sh.WriteLog("获取到参数：cParaId=" + cParaId);
                sh.WriteLog("获取到参数：desc=" + desc);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 对比数据
        [HttpPost]
        public HttpResponseMessage GetInverterStatistics()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string sid = request.Form["sid"];
            string startTime = request.Form["startTime"];
            string endTime = request.Form["endTime"];
            string type = request.Form["type"];
            try
            {
                InverterModel im;
                DataTable dt = new DataTable();
                List<Hashtable> lists = new List<Hashtable>();
                Dictionary<string, object> dic = new Dictionary<string, object>();
                string name = "";
                object ob = new { };
                StationModel sm = new StationModel(sid);
                DataTable dtInverter = sm.DtInverters;// GetInverterDataTable(sid);
                if (dtInverter != null && dtInverter.Rows.Count > 0)
                {
                    DateTime eTime = Convert.ToDateTime(endTime);
                    if (endTime == DateTime.Now.ToString("yyyy/MM/dd"))
                    {
                        eTime = DateTime.Now;
                    }
                    else
                    {
                        eTime = eTime.AddDays(1).AddSeconds(-1);
                    }
                    endTime = eTime.ToString("yyyy/MM/dd HH:mm:ss");
                    foreach (DataRow item in dtInverter.Rows)
                    {
                        string inverterId = item["T_UNITID"].ToString();
                        string inverterName = item["T_UNITDESC_CN"].ToString();
                        Hashtable ht = new Hashtable();
                        if (type != "Temperature")
                        {
                            int stringCount = Convert.ToInt32(item["Total"]);
                            double d = 0;
                            im = new InverterModel(inverterId, startTime, endTime);
                            if (type == "TotalElectricQuantity")
                            {
                                d = Convert.ToDouble((im.Elect / stringCount / 5).ToString("F2"));
                                name = "累计发电量";
                            }
                            else if (type == "AvgPower")
                            {
                                d = Convert.ToDouble((im.InverterAvgPower / stringCount / 5).ToString("F2"));
                                name = "平均功率";
                            }
                            else if (type == "AvgEfficiency")
                            {
                                d = im.InterverAvgEfficiency;
                                name = "发电效率";
                            }

                            ht.Add("name", inverterName);
                            ht.Add("data", d);
                            lists.Add(ht);
                        }
                        else
                        {
                            DateTime sTime = Convert.ToDateTime(startTime);
                            eTime = Convert.ToDateTime(endTime);

                            im = new InverterModel(inverterId, sTime, eTime, 2880);

                            ht.Add("name", inverterName);
                            ht.Add("data", im.Temps);
                            lists.Add(ht);
                        }
                    }

                }
                if (type != "Temperature")
                {
                    dic.Add("name", name);
                    dic.Add("data", lists);
                    double avgValue = 0;
                    if (lists.Count != 0)
                    {
                        avgValue = Convert.ToDouble(lists.Select(t => double.Parse(t["data"].ToString())).Average().ToString("f2"));
                    }
                    //var dataList = lists.Select(t => double.Parse(t["data"].ToString()));
                    //dic.Add("avg", double.Parse(avgValue.ToString("n2")));
                    OtherModel om = new OtherModel();
                    double warning = Convert.ToDouble(om.ObjWaringPara ?? 0);
                    double fault = Convert.ToDouble(om.ObjFaultPara ?? 0);
                    double warnValue = Convert.ToDouble((avgValue * (100 - warning) / 100).ToString("f2"));
                    double faultValue = Convert.ToDouble((avgValue * (100 - fault) / 100).ToString("f2"));
                    ob = new
                    {
                        list = dic,
                        avg = avgValue,
                        fault = faultValue,
                        warn = warnValue
                    };
                }
                else
                {
                    ob = new
                    {
                        list = lists
                    };

                }
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(ob);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetInverterStatistics");
                sh.WriteLog("获取到参数：sid=" + sid);
                sh.WriteLog("获取到参数：startTime=" + startTime);
                sh.WriteLog("获取到参数：endTime=" + endTime);
                sh.WriteLog("获取到参数：type=" + type);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #endregion

        #region 逆变器故障对比

        #region 故障对比数据
        [HttpPost]
        public HttpResponseMessage GetInverterFault()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string stationId = request.Form["stationId"];
            string startTime = request.Form["startTime"];
            string endTime = request.Form["endTime"];
            try
            {
                DataTable dtInverters = GetInverterDataTable(stationId);
                DateTime startDate = DateTime.Parse(startTime);
                DateTime endDate = DateTime.Parse(endTime + " 23:59:59");
                StationModel sm = new StationModel(stationId, startDate, endDate);
                DataTable dt = sm.DtDtFaultRecordCount;
                DeviceModel dm = new DeviceModel();
                List<Hashtable> listFault = dm.List.ToList();
                string strInverters = "";
                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                List<string> lst = new List<string>();
                if (dtInverters != null && dtInverters.Rows.Count > 0)
                {
                    int count = dtInverters.Rows.Count;
                    foreach (var item in listFault)
                    {
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        dic.Add("name", item["T_TYPEDESC"]);
                        int[] arr = new int[count];
                        for (int i = 0; i < count; i++)
                        {
                            string inverterName = dtInverters.Rows[i]["T_UNITDESC_CN"].ToString();
                            string inverterId = dtInverters.Rows[i]["T_UNITID"].ToString();
                            if (!lst.Contains(inverterName))
                            {
                                strInverters += inverterName + ",";
                                lst.Add(inverterName);
                            }
                            var num = dt.AsEnumerable().Where(p => p["T_TYPEID"].Equals(item["T_TYPEID"].ToString()) && p["T_ORGID"].ToString().Equals(inverterId)).Sum(p => int.Parse(p["num"].ToString()));
                            arr[i] = num;
                        }
                        dic.Add("data", arr);
                        list.Add(dic);
                    }
                }
                list.Reverse();
                if (strInverters.Length > 0)
                {
                    strInverters = strInverters.Substring(0, strInverters.Length - 1);
                }
                object obj = new
                {
                    inverter = strInverters,
                    data = list
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetInverterFault");
                sh.WriteLog("获取到参数：sid=" + stationId);
                sh.WriteLog("获取到参数：startTime=" + startTime);
                sh.WriteLog("获取到参数：endTime=" + endTime);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region  区域信息
        public DataTable GetInverterDataTable(string stationId)
        {
            StationModel sm = new StationModel(stationId);
            DataTable dtDistrict = sm.InverterInfo;
            string disIds = "";
            if (dtDistrict != null && dtDistrict.Rows.Count > 0)
            {
                foreach (DataRow dr in dtDistrict.Rows)
                {
                    disIds += "'" + dr["T_DISTRICTID"].ToString() + "',";
                }
            }
            if (disIds.Length > 0)
            {
                disIds = disIds.Substring(0, disIds.Length - 1);
            }
            DistrictModel dm = new DistrictModel(disIds);
            DataTable dtInverter = dm.Invertors;
            return dtInverter;
        }
        #endregion

        #endregion

        #region 逆变器类型故障对比
        [HttpPost]
        public HttpResponseMessage GetEquipTypeTree()
        {
            try
            {
                dtZtree = new DataTable();
                dtZtree.Columns.Add("tid", Type.GetType("System.String")); ;
                dtZtree.Columns.Add("pid", Type.GetType("System.String"));
                dtZtree.Columns.Add("dcn", Type.GetType("System.String"));
                DeviceModel dm = new DeviceModel();
                DataTable dt = dm.DtDevice;
                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                if (dt != null && dt.Rows.Count > 0)
                {

                    DataTable dtChild = dt.Select("T_TYPEID='nbq'").CopyToDataTable();
                    if (dtChild != null && dtChild.Rows.Count > 0)
                    {
                        dtZtree.Rows.Add(dtChild.Rows[0]["T_TYPEID"].ToString(), "00", dtChild.Rows[0]["T_TYPEDESC_CN"].ToString());
                        var companyList = dtChild.AsEnumerable().Where(p => p["T_TYPEID"].ToString().Equals("nbq"))
                                        .Select(p => new { companyId = p["T_COMPANYID"].ToString(), companyNameCn = p["T_COMPANYDESC_CN"].ToString() }).Distinct();
                        foreach (var item in companyList)
                        {
                            dtZtree.Rows.Add(item.companyId, "nbq", item.companyNameCn);
                        }
                        foreach (DataRow item in dtChild.Rows)
                        {
                            string machineId = item["T_MACHINEID"].ToString();
                            dtZtree.Rows.Add(machineId, item["T_COMPANYID"].ToString(), machineId);
                        }
                    }
                }
                foreach (DataRow dr in dtZtree.Rows)
                {
                    Dictionary<string, object> dic = new Dictionary<string, object>();
                    dic = new Dictionary<string, object>();
                    dic.Add("id", dr["tid"].ToString());
                    dic.Add("pId", dr["pid"].ToString());
                    dic.Add("name", dr["dcn"].ToString());
                    list.Add(dic);
                }
                object obj = new
                {
                    data = list

                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetEquipTypeTree");
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 组串对比

        #region 编辑故障原因或解决方案
        [HttpPost]
        public HttpResponseMessage FaultEdit()
        {
            bool judge = false;
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string resion = request.Form["resion"];
            string plant = request.Form["plant"];
            string id = request.Form["id"];
            try
            {
                DeviceModel dm = new DeviceModel(id, resion, plant);
                judge = dm.BlFault;
                object obj = new
                {
                    judge = judge
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetEquipTypeTree");
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 获取故障列表
        [HttpPost]
        public HttpResponseMessage FaultList()
        {
            int intPageSize = 10, intPageIndex = 1, total = 0;
            StringBuilder sbTable = new StringBuilder();

            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string user = request.Form["userId"];
            string type = request.Form["type"];
            string name = request.Form["name"];
            string strStationId = request.Form["stationID"];
            string eTime = request.Form["et"];
            string sTime = request.Form["st"];
            intPageSize = Convert.ToInt32(request.Form["pageSize"]);
            intPageIndex = Convert.ToInt32(request.Form["pageIndex"]);
            try
            {
                if (type == "所有故障")
                    type = "";

                OrgModel om = new OrgModel(user);

                DataTable dtStation = om.DtUserStation;
                if (dtStation != null && dtStation.Rows.Count > 0)
                {
                    if (strStationId == "" || strStationId == null)
                    {
                        for (int i = 0; i < dtStation.Rows.Count; i++)
                        {
                            strStationId += "'" + dtStation.Rows[i]["T_ORGID"] + "',";
                        }

                        strStationId = strStationId.Substring(0, strStationId.Length - 1);      //电站ID
                    }
                    StationModel sm = new StationModel(strStationId, Convert.ToDateTime(sTime), Convert.ToDateTime(eTime), name, type, intPageSize, intPageIndex);
                    int intCount = sm.FaultDetailInfoListCount;

                    if (intCount % intPageSize == 0)
                        total = intCount / intPageSize;
                    else
                        total = intCount / intPageSize + 1;

                    dtStation = sm.DtFaultDetailInfoList;

                    if (dtStation != null && dtStation.Rows.Count > 0)
                    {
                        sbTable.Append("<table width=\"100%\"  border=\"0\" cellpadding=\"0\" cellspacing=\"0\">");

                        for (int i = 0; i < dtStation.Rows.Count; i++)
                        {
                            sbTable.Append("<tr class=\"tr_2\">");
                            sbTable.Append("<td width = \"3%\" class=\"td_2_l\"><span id = \"sp_order\" >" + (i + 1) + "</ span ></ td >");
                            sbTable.Append("<td width = \"8%\" class=\"td_2_c\"><span id = \"sp_order\">" + dtStation.Rows[i]["T_CITYDESC"] + " </ span ></ td >");
                            sbTable.Append("<td width=\"8%\" class=\"td_2_c\"><span id = \"sp_name\" > " + dtStation.Rows[i]["T_PLANTDESC"] + " </ span ></ td >");
                            sbTable.Append("<td width=\"10%\" class=\"td_2_c\"><span id = \"sp_name\" > " + dtStation.Rows[i]["T_UNITDESC_CN"] + " </ span ></ td >");
                            sbTable.Append("<td width=\"10%\" class=\"td_2_c\"><span id = \"sp_desc\" > " + dtStation.Rows[i]["T_TYPEDESC"] + " </ span ></ td >");
                            sbTable.Append("<td width=\"10%\" class=\"td_2_c\"><span id = \"sp_desc\" > " + dtStation.Rows[i]["T_FAULTDESC_CN"] + " </ span ></ td >");
                            sbTable.Append("<td width=\"15%\" class=\"td_2_c\"><span id = \"sp_desc\" > " + dtStation.Rows[i]["T_STARTTIME"] + " </ span ></ td >");
                            sbTable.Append("<td width=\"15%\" class=\"td_2_c\"><span id = \"sp_desc\" > " + dtStation.Rows[i]["T_ENDTIME"] + " </ span ></ td >");


                            if (dtStation.Rows[i].IsNull("T_ENDTIME"))
                                sbTable.Append("<td width=\"5%\" class=\"td_2_c\"><span id = \"sp_desc\" >  </ span ></ td >");
                            else
                            {
                                int day = Convert.ToDateTime(dtStation.Rows[i]["T_ENDTIME"].ToString()).Day - Convert.ToDateTime(dtStation.Rows[i]["T_STARTTIME"].ToString()).Day;
                                double hour = Convert.ToDateTime(dtStation.Rows[i]["T_ENDTIME"].ToString()).Hour - Convert.ToDateTime(dtStation.Rows[i]["T_STARTTIME"].ToString()).Hour;
                                int min = Convert.ToDateTime(dtStation.Rows[i]["T_ENDTIME"].ToString()).Minute - Convert.ToDateTime(dtStation.Rows[i]["T_STARTTIME"].ToString()).Minute;

                                if (min < 0)
                                {
                                    hour -= 1;
                                    min += 60;
                                }
                                if (hour < 0)
                                {
                                    day -= 1;
                                    hour += 24;
                                }
                                hour = sh.GetDouble(hour, 1);
                                if (day != 0)
                                    sbTable.Append("<td width=\"5%\" class=\"td_2_c\"><span id = \"sp_desc\" > " + (day) + "&nbsp;&nbsp;天&nbsp;&nbsp;" + (hour) + "&nbsp;&nbsp;小时 </ span ></ td >");
                                else
                                {
                                    sbTable.Append("<td width=\"5%\" class=\"td_2_c\"><span id = \"sp_desc\" > " + (hour) + "&nbsp;&nbsp;小时 </ span ></ td >");
                                }
                            }
                            sbTable.Append("<td width=\"5%\" class=\"td_2_c\"><span id = \"sp_btn\" class=\"button_table\"  onclick=\"ClickDialog('" + dtStation.Rows[i]["T_FAULTID"] + "')\"> 处理 </ span ></ td >");
                            sbTable.Append("<td width=\"5%\" class=\"td_2_r\"><span id = \"sp_btn\"  class=\"button_table\" > 操作票 </ span ></ td >");
                            sbTable.Append("</tr>");
                        }
                        sbTable.Append("</table>");
                    }
                }
                object obj = new
                {
                    total = total,
                    table = sbTable.ToString()
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：FaultList");
                sh.WriteLog("参数：userId" + user);
                sh.WriteLog("参数：type" + type);
                sh.WriteLog("参数：stationID" + strStationId);
                sh.WriteLog("参数：st" + sTime);
                sh.WriteLog("参数：et" + eTime);
                sh.WriteLog("参数：pageSize" + intPageSize);
                sh.WriteLog("参数：pageIndex" + intPageIndex);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 设备故障类型
        [HttpPost]
        public HttpResponseMessage InitFault()
        {
            try
            {
                DeviceModel dm = new DeviceModel();
                IList<Hashtable> list = dm.List;
                object obj = new
                {
                    list = list
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：InitFault");
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 获取故障原因或解决方案
        [HttpPost]
        public HttpResponseMessage FaultResionAndPlant()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string id = request.Form["faultId"];
            try
            {
                IList<Hashtable> list = new List<Hashtable>();
                DeviceModel dm = new DeviceModel(id);
                Hashtable ht = new Hashtable();
                ht.Add("resion", dm.ObjFaultReason);
                ht.Add("plant", dm.ObjFaultProposal);
                list.Add(ht);

                object obj = new
                {
                    list = list
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：FaultResionAndPlant");
                sh.WriteLog("参数：faultId" + id);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #endregion

        #region 电站性能分析
        [HttpPost]
        public HttpResponseMessage GetStationStatistics()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string sid = request.Form["sid"];
            int sYear = Convert.ToInt32(request.Form["startTime"]);
            int eYear = Convert.ToInt32(request.Form["endTime"]);
            string type = request.Form["type"];
            try
            {

                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                if (type == "TotalElectricQuantity" || type == "AvgPower")
                {
                    DateTime start = new DateTime(sYear, 1, 1, 0, 0, 0);
                    DateTime end = new DateTime(eYear, 1, 1, 0, 0, 0).AddYears(1).AddSeconds(-1);
                    StationModel sm = new StationModel(sid, start, end);
                    DataTable dt;
                    if (type == "AvgPower")
                    {
                        dt = sm.DtMonthAvgPower;
                    }
                    else
                    {
                        dt = sm.DtTotalMonthDL;
                    }
                    var dlList = dt.AsEnumerable();
                    for (int i = sYear; i <= eYear; i++)
                    {
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        double?[] ds = new double?[12];
                        for (int j = 0; j < 12; j++)
                        {
                            if (new DateTime(i, j + 1, 1) > DateTime.Now)
                            {
                                ds[j] = null;
                                continue;
                            }
                            var current = dlList.Where(p => p["年"].ToString().Equals(i.ToString()) && p["月"].ToString() == (j + 1).ToString());
                            if (current != null && current.Count() > 0)
                            {
                                ds[j] = Math.Round(current.Select(t => Convert.ToDouble(t["合计"])).ToList()[0], 2);
                            }
                            else
                            {
                                ds[j] = 0;
                            }
                        }
                        dic.Add("name", i.ToString());
                        dic.Add("data", ds);
                        list.Add(dic);
                    }
                }
                else
                {
                    for (int i = sYear; i <= eYear; i++)
                    {
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        double?[] ds = new double?[12];
                        for (int j = 1; j < 13; j++)
                        {
                            DateTime start = new DateTime(i, j, 1);
                            DateTime end = start.AddMonths(1).AddSeconds(-1);
                            ds[j - 1] = null;
                        }
                        dic.Add("name", i.ToString());
                        dic.Add("data", ds);
                        list.Add(dic);
                    }
                }

                object obj = new
                {
                    list = list
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetStationStatistics");
                sh.WriteLog("参数：sid" + sid);
                sh.WriteLog("参数：startTime" + sYear);
                sh.WriteLog("参数：endTime" + eYear);
                sh.WriteLog("参数：type" + type);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 电站性能对比

        #region 年
        [HttpPost]
        public HttpResponseMessage GetStationsCompareByYear()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string sids = request.Form["sids"];
            string snames = request.Form["snames"];
            string startTime = request.Form["startTime"];
            string endTime = request.Form["endTime"];
            string type = request.Form["type"];
            try
            {
                List<Dictionary<string, object>> lst = new List<Dictionary<string, object>>();
                string[] idsArr = sids.Split(',');
                string[] namesArr = snames.Split(',');
                int startYear = int.Parse(startTime);
                int endYear = int.Parse(endTime);
                Dictionary<string, object> dic;
                string stationIds = "";
                for (int i = 0; i < idsArr.Length; i++)
                {
                    stationIds += "'" + idsArr[i] + "',";
                }
                if (stationIds.Length > 1)
                {
                    stationIds = stationIds.Trim(',');
                }
                StationModel sm1 = new StationModel(stationIds);
                DataTable dtStationRl = sm1.AllRL;
                double?[] dou = new double?[endYear - startYear + 1];
                for (int j = 0; j < idsArr.Length; j++)
                {
                    if (type == "unitDL")
                    {
                        StationModel sm = new StationModel(idsArr[j], new DateTime(startYear, 1, 1, 0, 0, 0), new DateTime(endYear, 12, 31, 23, 59, 59));
                        dic = new Dictionary<string, object>();
                        var rllist = dtStationRl.AsEnumerable().Where(p => p["T_ORGID"].ToString() == idsArr[j]);
                        if (rllist == null || rllist.Count() == 0)
                        {
                            continue;
                        }
                        double dlRl = Convert.ToDouble(rllist.Select(p => p["d_rl"].ToString()).ToList()[0]);

                        DataTable dt = sm.DtTotalYearDL;
                        var dlList = dt.AsEnumerable();
                        for (int i = 0; i <= endYear - startYear; i++)
                        {
                            if (new DateTime(i + startYear, 1, 1) > DateTime.Now)
                            {
                                dou[i] = null;
                                continue;
                            }
                            var yearDl = dlList.Where(p => p["年"].ToString() == (i + startYear).ToString()).Select(t => t["合计"]);
                            if (yearDl != null && yearDl.Count() > 0)
                            {
                                dou[i] = Convert.ToDouble((Convert.ToDouble(yearDl.ToList()[0]) / dlRl).ToString("f2"));
                            }
                            else
                            {
                                dou[i] = 0;
                            }
                        }
                    }
                    else
                    {
                        StationModel sm = new StationModel(idsArr[j]);
                        dic = new Dictionary<string, object>();
                        for (int i = 0; i <= endYear - startYear; i++)
                        {
                            DateTime startDate = new DateTime(i + startYear, 1, 1);
                            DateTime endDate = startDate.AddYears(1).AddSeconds(-1);
                            dou[i] = GetStationData(idsArr[j], startDate, endDate, type);
                        }
                    }
                    dic.Add("name", namesArr[j]);
                    dic.Add("data", dou);
                    lst.Add(dic);
                }
                object obj = new
                {
                    dataList = lst
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetStationStatistics");
                sh.WriteLog("参数：sids" + sids);
                sh.WriteLog("参数：snames" + snames);
                sh.WriteLog("参数：startTime" + startTime);
                sh.WriteLog("参数：endTime" + endTime);
                sh.WriteLog("参数：type" + type);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 性能区别
        [HttpPost]
        public double GetStationData(string sid, DateTime startDate, DateTime endDate, string type)
        {
            StationModel sm = new StationModel(sid, startDate, endDate);
            double d = 0;
            switch (type)
            {
                case "unitDL":
                    d = sm.UnitDL;
                    break;
                case "efficiency":
                    d = sm.SumEfficiency;
                    break;
                case "systemEfficiency":
                    d = sm.SystemEfficiency;
                    break;
                case "conversionEfficiency":
                    d = sm.ConversionEfficiency;
                    break;
            }
            return d;
        }
        #endregion

        #endregion

        #region 电量损失分析

        #region 电损数据
        [HttpPost]
        public HttpResponseMessage Chart()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string id = request.Form["id"];
            try
            {
                IList<Hashtable> list = new List<Hashtable>();
                Hashtable ht = new Hashtable();
                Random rd = new Random();
                ht.Add("name", "上网电量");
                ht.Add("id", "1");
                ht.Add("y", 801);
                //ht.Add("sliced", true);
                //ht.Add("selected", true);
                //if (id == null || id == "")
                //    ht.Add("url", "Chart/EnergyLoseTable?id=1");
                //else
                ht.Add("url", "EnergyLoseTable?id=1");
                list.Add(ht);

                ht = new Hashtable();
                ht.Add("name", "光伏方阵吸收损耗");
                ht.Add("id", "2");
                ht.Add("y", 136);
                //if (id == null || id == "")
                //    ht.Add("url", "Chart/EnergyLoseTable?id=2");
                //else
                ht.Add("url", "EnergyLoseTable?id=2");
                list.Add(ht);

                ht = new Hashtable();
                ht.Add("name", "逆变器损耗");
                ht.Add("id", "3");
                ht.Add("y", 37);
                //if (id == null || id == "")
                //    ht.Add("url", "Chart/EnergyLoseTable?id=3");
                //else
                ht.Add("url", "EnergyLoseTable?id=3");
                list.Add(ht);

                ht = new Hashtable();
                ht.Add("name", "集电线路及箱变损耗");
                ht.Add("id", "4");
                ht.Add("y", 18);
                //if (id == null || id == "")
                //    ht.Add("url", "Chart/EnergyLoseTable?id=4");
                //else
                ht.Add("url", "EnergyLoseTable?id=4");
                list.Add(ht);

                ht = new Hashtable();
                ht.Add("name", "升压站损耗");
                ht.Add("id", "5");
                ht.Add("y", 8);
                //if (id == null || id == "")
                //    ht.Add("url", "Chart/EnergyLoseTable?id=5");
                //else
                ht.Add("url", "EnergyLoseTable?id=5");
                list.Add(ht);

                object obj = new
                {
                    chart = list
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetStationStatistics");
                sh.WriteLog("参数：id" + id);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 电损表格
        [HttpPost]
        public HttpResponseMessage InitEnergyLoseTable()
        {
            StringBuilder sd = new StringBuilder();
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string id = request.Form["id"];
            string lg = request.Form["lg"];
            try
            {
                string temperature = "";
                string fzd = "";

                ArrayList altm = new ArrayList();
                ArrayList alfd = new ArrayList();


                if (id == "2")
                {
                    sd.Append("<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\" border='0'>");
                    sd.Append("<tr class=\"tr_2\">");
                    sd.AppendFormat("<td width=\"5%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", 1);
                    sd.AppendFormat("<td width=\"15%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", "电站1");
                    sd.AppendFormat("<td width=\"10%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", "电站1一期");
                    sd.AppendFormat("<td width=\"20%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", "逆变器故障");
                    sd.AppendFormat("<td width=\"20%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
                    sd.AppendFormat("<td width=\"20%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    sd.AppendFormat("<td width=\"10%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", ReturnSeconds(Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 0:00:00")), DateTime.Now));
                    sd.Append("</tr>");
                    sd.Append("</table>");
                }
                else if (id == "4")
                {
                    sd.Append("<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\" border='0'>");
                    sd.Append("<tr class=\"tr_2\">");
                    sd.AppendFormat("<td width=\"5%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", 1);
                    sd.AppendFormat("<td width=\"15%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", "电站1");
                    sd.AppendFormat("<td width=\"10%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", "电站1一期");
                    sd.AppendFormat("<td width=\"20%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", "限电");
                    sd.AppendFormat("<td width=\"20%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
                    sd.AppendFormat("<td width=\"20%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    sd.AppendFormat("<td width=\"10%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", ReturnSeconds(Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 0:00:00")), DateTime.Now));
                    sd.Append("</tr>");
                    sd.Append("</table>");
                }
                else if (id == "5")
                {
                    sd.Append("<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\" border='0'>");
                    sd.Append("<tr class=\"tr_2\">");
                    sd.AppendFormat("<td width=\"5%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", 1);
                    sd.AppendFormat("<td width=\"15%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", "电站1");
                    sd.AppendFormat("<td width=\"10%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", "电站1一期");
                    sd.AppendFormat("<td width=\"20%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", "检修");
                    sd.AppendFormat("<td width=\"20%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
                    sd.AppendFormat("<td width=\"20%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    sd.AppendFormat("<td width=\"10%\" class='td_1' valign='middle' height ='30px' align='center'>{0}</td>", ReturnSeconds(Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 0:00:00")), DateTime.Now));
                    sd.Append("</tr>");
                }
                else if (id == "1" || id == "3")
                {
                    Random rd = new Random();

                    for (int i = 0; i < 96; i++)
                    {
                        altm.Add(rd.Next(26, 30));
                        alfd.Add(rd.Next(800, 1000));
                        temperature += rd.Next(26, 30) + ",";
                        fzd += rd.Next(800, 1000) + ",";
                    }
                    temperature = "[" + temperature.Substring(0, temperature.Length - 1) + "]";
                    fzd = "[" + fzd.Substring(0, fzd.Length - 1) + "]";
                }

                object obj = new
                {
                    id = id,
                    tbl = sd.ToString(),
                    temperature = temperature,
                    fzd = fzd,
                    tm = altm,
                    fd = alfd
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetStationStatistics");
                sh.WriteLog("参数：id" + id);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 时间转换
        private int ReturnSeconds(DateTime st, DateTime et)
        {
            TimeSpan ts1 = new TimeSpan(st.Ticks);
            TimeSpan ts2 = new TimeSpan(et.Ticks);

            TimeSpan ts = et - st;
            return (int)ts.TotalSeconds;
        }
        #endregion

        #endregion

        #region 故障对比
        [HttpPost]
        public HttpResponseMessage GetFaultFrequencyData()
        {
            StringBuilder sd = new StringBuilder();
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string stationIds = request.Form["stationIds"];
            string startTime = request.Form["startTime"];
            string endTime = request.Form["endTime"];
            try
            {
                DateTime startDate = DateTime.Parse(startTime);
                DateTime endDate = DateTime.Parse(endTime + " 23:59:59");
                StationModel sm = new StationModel(stationIds, startDate, endDate);
                DataTable dt = sm.DtDtFaultRecordCount;

                sm = new StationModel(stationIds);
                DataTable dtInverter = sm.DtInverters;
                var inverterType = dt.AsEnumerable().Where(p => p["T_MACHINEID"].ToString() != "").Select(p => new { typeId = p["T_MACHINEID"].ToString() }).Distinct();
                var faultType = dt.AsEnumerable().Select(p => new { id = p["T_TYPEID"].ToString(), name = p["T_TYPEDESC"].ToString() }).Distinct().OrderBy(p => p.id).ToList();
                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                string strType = "";
                if (faultType != null)
                {
                    foreach (var item in faultType)
                    {
                        string name = item.name;
                        strType += name + ",";
                    }
                }
                if (strType.Length > 0)
                {
                    strType = strType.Substring(0, strType.Length - 1);
                }
                if (inverterType != null)
                {
                    foreach (var item in inverterType)
                    {
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        dic.Add("name", item.typeId);
                        int count = faultType.Count();
                        double[] dou = new double[count];
                        for (int i = 0; i < count; i++)
                        {
                            int curInverterTypeCount = dtInverter.AsEnumerable().Where(p => p["T_MACHINEID"].Equals(item.typeId)).Count();
                            var record = dt.AsEnumerable().Where(p => p["T_TYPEID"].Equals(faultType[i].id) && p["T_MACHINEID"].ToString().Equals(item.typeId)).Select(p => new { num = int.Parse(p["num"].ToString()) });
                            if (record.Count() > 0)
                            {
                                dou[i] = double.Parse(((double)(record.Sum(p => p.num)) / ((double)curInverterTypeCount)).ToString("f2"));
                            }
                            else
                            {
                                dou[i] = 0;
                            }
                        }
                        dic.Add("data", dou);
                        list.Add(dic);
                    }
                }

                object obj = new
                {
                    data = list,
                    xAxis = strType.Split(',')
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetStationStatistics");
                sh.WriteLog("参数：stationIds" + stationIds);
                sh.WriteLog("参数：startTime" + startTime);
                sh.WriteLog("参数：endTime" + endTime);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #endregion

        #region 数据分析

        #region 自定义趋势

        #region 趋势列表

        #region 删除模板
        [HttpPost]
        public HttpResponseMessage DelModel()
        {
            bool blJudge = false;
            StringBuilder sd = new StringBuilder();
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string mid = request.Form["id"];
            try
            {
                ChartModel cmd = new ChartModel(mid);

                blJudge = cmd.Del;
                object obj = new
                {
                    result = blJudge
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：DelModel");
                sh.WriteLog("参数：mid" + mid);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 初始化趋势列表
        [HttpPost]
        public HttpResponseMessage TrendList()
        {
            int intPageSize = 10, intPageIndex = 1, total = 0;
            StringBuilder sd = new StringBuilder();
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            int pageSize = Convert.ToInt32(request.Form["pageSize"]);
            int pageIndex = Convert.ToInt32(request.Form["pageIndex"]);
            string user = request.Form["userId"];
            try
            {


                DataTable dtModel = new DataTable();
                ChartModel cm = new ChartModel(user);
                int intCount = cm.CountModel;

                if (intCount % intPageSize == 0)
                    total = intCount / intPageSize;
                else
                    total = intCount / intPageSize + 1;

                cm = new ChartModel(intPageSize, intPageIndex, user);
                dtModel = cm.DtModel;

                StringBuilder sbTable = new StringBuilder();
                if (dtModel != null && dtModel.Rows.Count > 0)
                {
                    sbTable.Append("<table width=\"100%\"  border=\"0\" cellpadding=\"0\" cellspacing=\"0\">");
                    string strOdd = "";
                    for (int i = 0; i < dtModel.Rows.Count; i++)
                    {
                        if (i % 2 == 0)
                        {
                            strOdd = "1";
                        }
                        else
                        {
                            strOdd = "2";
                        }
                        sbTable.Append("<tr class=\"tr_2\">");
                        sbTable.Append("<td width=\"10%\" class=\"td_2_l\">" + ((intPageIndex - 1) * intPageSize + i + 1) + "</td>");
                        //sbTable.Append("<td width=\"35%\" class=\"td_2_c\">" + dtModel.Rows[i][1] + "</td>");
                        sbTable.Append("<td width=\"70%\" class=\"td_2_c\">" + dtModel.Rows[i][2] + "</td>");
                        sbTable.Append("<td width=\"20%\" class=\"td_2_r\" >");
                        sbTable.Append("<div id=\"toolbar_" + i + "\" class=\"td_toolbar\">");
                        sbTable.Append("<div class=\"btn_td_view\" onclick=returnNext('" + dtModel.Rows[i][1] + "','" + dtModel.Rows[i][3] + "','" + dtModel.Rows[i][4] + "','" + dtModel.Rows[i][5] + "','" + dtModel.Rows[i][6] + "')></div>");
                        sbTable.Append("<div class=\"btn_td_edit\" onclick=returnNext('" + dtModel.Rows[i][1] + "','" + dtModel.Rows[i][3] + "','" + dtModel.Rows[i][4] + "','" + dtModel.Rows[i][5] + "','" + dtModel.Rows[i][6] + "')></div>");
                        sbTable.Append("<div class=\"btn_td_del\" onclick=delModel('" + dtModel.Rows[i][1] + "')></div>");
                        sbTable.Append("</div></td>");
                        sbTable.Append("</tr>");
                    }
                    sbTable.Append("</table>");
                }
                object obj = new
                {
                    total = total,
                    table = sbTable.ToString()
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：DelModel");
                sh.WriteLog("参数：pageSize" + pageSize);
                sh.WriteLog("参数：pageIndex" + pageIndex);
                sh.WriteLog("参数：userId" + user);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region Tree 查询
        [HttpPost]
        public HttpResponseMessage GetSearchTree()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string key = request.Form["key"];
            string userid = request.Form["uid"];
            try
            {
                OrgModel om = new OrgModel(userid);

                DataTable dtCity = new DataTable();
                DataTable dtAllOrg = new DataTable();
                DataTable dtUserAuthorization = new DataTable();

                dtCity = om.DtCity;                             //组织机构
                dtAllOrg = om.DtUserStation;                    //用户与电站关系
                dtUserAuthorization = om.DtAllOrgInfo;          //所有电站

                string strStationId = "";
                for (int i = 0; i < dtAllOrg.Rows.Count; i++)
                {
                    strStationId += "'" + dtAllOrg.Rows[i]["T_ORGID"] + "',";
                }
                strStationId = strStationId.Substring(0, strStationId.Length - 1);
                DataRow[] drStation = dtUserAuthorization.Select("T_ORGID in (" + strStationId + ")");    //电站  

                if (strStationId.IndexOf(',') <= -1) { strStationId = strStationId.Replace("'", ""); }
                InverterModel im = new InverterModel(strStationId);
                DataTable dtPoints = im.Points;
                if (dtPoints != null)
                    for (int i = 0; i < dtPoints.Rows.Count; i++)
                    {
                        DataRow dr;
                        dr = dtZtree.NewRow();
                        dr["tid"] = dtPoints.Rows[i]["T_PARAID"];
                        dr["pid"] = dtPoints.Rows[i]["T_ORGID"];
                        dr["dcn"] = dtPoints.Rows[i]["T_PARADESC_CN"];
                        dr["den"] = dtPoints.Rows[i]["T_PARADESC_EN"];
                        dr["point"] = dtPoints.Rows[i]["T_REALTIME"];
                        dtZtree.Rows.Add(dr);
                    }

                string strCityID = "";

                foreach (DataRow dr in drStation)
                {
                    strCityID += "'" + dr["T_CITYID"] + "',";
                    DataRow drw = dtZtree.NewRow();
                    drw["tid"] = dr["T_ORGID"];
                    drw["pid"] = dr["T_CITYID"];
                    drw["dcn"] = dr["T_PLANTDESC"];
                    drw["point"] = "";
                    dtZtree.Rows.Add(drw);
                }
                strCityID = "(" + strCityID.Substring(0, strCityID.Length - 1) + ")";               //市ID
                DataRow[] drCity = dtCity.Select("T_CITYID in " + strCityID);                       //市

                string strPrivinceID = "";
                foreach (DataRow dr in drCity)
                {
                    strPrivinceID += "'" + dr["T_PARENTID"] + "',";
                    DataRow drw = dtZtree.NewRow();
                    drw["tid"] = dr["T_CITYID"];
                    drw["pid"] = dr["T_PARENTID"];
                    drw["dcn"] = dr["T_CITYDESC"];
                    drw["point"] = "";
                    dtZtree.Rows.Add(drw);
                }
                if (strPrivinceID != "")
                {
                    strPrivinceID = "(" + strPrivinceID.Substring(0, strPrivinceID.Length - 1) + ")";   //省ID
                    DataRow[] drPrivince = dtCity.Select("T_CITYID in " + strPrivinceID);

                    foreach (DataRow dr in drPrivince)
                    {
                        DataRow drw = dtZtree.NewRow();
                        drw["tid"] = dr["T_CITYID"];
                        drw["pid"] = dr["T_PARENTID"];
                        drw["dcn"] = dr["T_CITYDESC"];
                        drw["point"] = "";
                        dtZtree.Rows.Add(drw);
                    }
                }
                string strDis = "";
                DataTable dtDistraction = new DataTable();

                StationModel sm = new StationModel(strStationId);
                dtDistraction = sm.Distraction;

                if (dtDistraction != null && dtDistraction.Rows.Count > 0)
                    for (int i = 0; i < dtDistraction.Rows.Count; i++)
                    {
                        strDis += "'" + dtDistraction.Rows[i]["T_DISTRICTID"] + "',";
                        DataRow drw = dtZtree.NewRow();
                        drw["tid"] = dtDistraction.Rows[i]["T_DISTRICTID"];
                        drw["pid"] = dtDistraction.Rows[i]["T_ORGID"];
                        drw["dcn"] = dtDistraction.Rows[i]["T_DISTRICTDESC_CN"];
                        drw["point"] = "";
                        dtZtree.Rows.Add(drw);
                    }

                if (strDis != "")
                {
                    strDis = strDis.Substring(0, strDis.Length - 1);
                    if (strDis.IndexOf(',') <= -1) { strDis = strDis.Replace("'", ""); }
                    im = new InverterModel(strDis);
                    dtPoints = im.Points;
                    if (dtPoints != null)
                        for (int i = 0; i < dtPoints.Rows.Count; i++)
                        {
                            DataRow dr;
                            dr = dtZtree.NewRow();
                            dr["tid"] = dtPoints.Rows[i]["T_PARAID"];
                            dr["pid"] = dtPoints.Rows[i]["T_ORGID"];
                            dr["dcn"] = dtPoints.Rows[i]["T_PARADESC_CN"];
                            dr["den"] = dtPoints.Rows[i]["T_PARADESC_EN"];
                            dr["point"] = dtPoints.Rows[i]["T_REALTIME"];
                            dtZtree.Rows.Add(dr);
                        }
                }

                DataTable dtInverter = new DataTable();
                DistrictModel dm = new DistrictModel(strDis);
                //dtInverter = dm.Invertors;
                dtInverter = dm.DtDevice;
                string ivr = "";
                if (dtInverter != null && dtInverter.Rows.Count > 0)
                    for (int i = 0; i < dtInverter.Rows.Count; i++)
                    {
                        ivr += "'" + dtInverter.Rows[i]["T_UNITID"] + "',";
                        DataRow drw = dtZtree.NewRow();
                        drw["tid"] = dtInverter.Rows[i]["T_UNITID"];
                        drw["pid"] = dtInverter.Rows[i]["T_DISTRICTID"];
                        drw["dcn"] = dtInverter.Rows[i]["T_UNITDESC_CN"];
                        drw["point"] = "";
                        dtZtree.Rows.Add(drw);
                    }
                if (ivr != "")
                {
                    ivr = ivr.Substring(0, ivr.Length - 1);
                    if (ivr.IndexOf(',') <= -1) { ivr = ivr.Replace("'", ""); }
                }
                im = new InverterModel(ivr);

                dtPoints = im.Points;
                if (dtPoints != null)

                    for (int i = 0; i < dtPoints.Rows.Count; i++)
                    {
                        DataRow dr;
                        dr = dtZtree.NewRow();
                        dr["tid"] = dtPoints.Rows[i]["T_PARAID"];
                        dr["pid"] = dtPoints.Rows[i]["T_ORGID"];
                        dr["dcn"] = dtPoints.Rows[i]["T_PARADESC_CN"];
                        dr["den"] = dtPoints.Rows[i]["T_PARADESC_EN"];
                        dr["point"] = dtPoints.Rows[i]["T_REALTIME"];
                        dtZtree.Rows.Add(dr);
                    }


                DataRow[] drs = null;
                drs = dtZtree.Select("dcn like '%" + key + "%'");

                string tree = "";
                for (int i = 0; i < dtZtree.Rows.Count; i++)
                {
                    if (dtZtree.Rows[i]["point"] == null || dtZtree.Rows[i]["point"].ToString() == "")
                        tree += "{id:'" + dtZtree.Rows[i]["tid"] + "',pId:'" + dtZtree.Rows[i]["pid"] + "',nodeID:'" + dtZtree.Rows[i]["point"] + "',name:'" + dtZtree.Rows[i]["dcn"] + "',t:'" + dtZtree.Rows[i]["dcn"] + "',chkDisabled:true},";

                }

                if (drs.Length > 0)
                {
                    for (int i = 0; i < drs.Length; i++)
                    {
                        tree += "{id:'" + drs[i][1] + "',pId:'" + drs[i][2] + "',nodeID:'" + drs[i][5] + "',name:'" + drs[i][3] + "',t:'" + drs[i][3] + "'},";
                    }
                }

                if (tree.Length > 0 & tree != "")
                    tree = "[" + tree.Substring(0, tree.Length - 1) + "]";

                object obj = new
                {
                    tree = tree
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：DelModel");
                sh.WriteLog("参数：key" + key);
                sh.WriteLog("参数：uid" + userid);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #endregion

        #region 趋势展示



        #endregion

        #endregion

        #region 生产报表
        [HttpPost]
        public HttpResponseMessage DLSearchTable()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string _time = request.Form["time"];
            string userid = request.Form["uid"];
            try
            {

                DateTime pTime = Convert.ToDateTime(_time + " 23:50:00");
                OrgModel om = new OrgModel(userid);

                DataTable dtAllOrg = new DataTable();
                DataTable dtUserAuthorization = new DataTable();
                //组织机构
                dtAllOrg = om.DtUserStation;                    //用户与电站关系
                dtUserAuthorization = om.DtAllOrgInfo;          //所有电站

                string strStationId = "";
                for (int i = 0; i < dtAllOrg.Rows.Count; i++)
                {
                    strStationId += "'" + dtAllOrg.Rows[i]["T_ORGID"] + "',";
                }
                strStationId = strStationId.Substring(0, strStationId.Length - 1);      //电站ID

                StationModel sm = new StationModel(strStationId);

                DataRow[] drStation = dtUserAuthorization.Select("T_ORGID in (" + strStationId + ")");    //电站           

                string[] arr = drStation.Select(x => x["T_ORGID"].ToString()).ToArray();


                string _dl = "", _fz = "";
                StringBuilder sb = new StringBuilder();
                sb.Append("<table id=\"tb_list_body\" style=\"width:100%;height:100%;border:0px;\" cellpadding=\"0\" cellspacing=\"0\">");
                sb.Append("<tr class=\"tr_1\">");
                sb.Append("<td width=\"10%\" class=\"td_1_l\">序号</td>");
                sb.Append("<td width=\"13%\" class=\"td_1_c\">电站名称</td>");
                sb.Append("<td width=\"10%\" class=\"td_1_c\">发电量</td>");

                sb.Append("<td width=\"10%\" class=\"td_1_c\">辐照度</td></tr>");


                List<double[]> lt_powerdl = new List<double[]>();
                if (pTime.Date == DateTime.Now.Date)
                {
                    sm = new StationModel("'" + string.Join("','", arr) + "'", "电量,辐照度".Split(','));

                    lt_powerdl = sm.RealVal;
                }
                else
                {
                    sm = new StationModel("'" + string.Join("','", arr) + "'", pTime);
                    lt_powerdl = sm.ArrayHisDL;
                }
                for (int i = 0; i < dtAllOrg.Rows.Count; i++)
                {
                    int ar_num = Array.IndexOf(arr, dtAllOrg.Rows[i]["T_ORGID"].ToString());
                    _dl = "";
                    if (lt_powerdl[0][ar_num].ToString() != "非数字" && lt_powerdl[0][ar_num] != -99999)
                    {
                        _dl = Math.Round(lt_powerdl[0][ar_num], 2).ToString();
                    }
                    else
                    {
                        _dl = "未取到";
                    }

                    _fz = "";
                    if (lt_powerdl[1][ar_num].ToString() != "非数字" && lt_powerdl[0][ar_num] != -99999)
                    {
                        _fz = Math.Round(lt_powerdl[1][ar_num], 2).ToString();
                    }
                    else
                    {
                        _fz = "未取到";
                    }

                    sb.Append("<tr class=\"tr_2\">");
                    sb.Append("<td width=\"10%\" class=\"td_2_l\">" + (i + 1) + "</td>");
                    sb.Append("<td width=\"13%\" class=\"td_2_c\">" + dtAllOrg.Rows[i]["T_PLANTDESC"].ToString() + "</td>");
                    sb.Append("<td width=\"10%\" class=\"td_2_c\">" + _dl + "</td>");
                    sb.Append("<td width=\"10%\" class=\"td_2_c\">" + _fz + "</td>");
                    sb.Append("</tr>");
                }
                sb.Append("</table>");
                object obj = new
                {
                    list = sb.ToString()
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：DLSearchTable");
                sh.WriteLog("参数：time" + _time);
                sh.WriteLog("参数：uid" + userid);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 电量一览
        [HttpPost]
        public HttpResponseMessage GetStationEnergys()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string sid = request.Form["sid"];
            string stationName = request.Form["stationName"];
            string startTime = request.Form["startTime"];
            string endTime = request.Form["endTime"];
            string dateType = request.Form["dateType"];
            try
            {
                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            StationModel sm = new StationModel(sid);
            bool isStation = sm.Check;
            if (isStation)
            {
                if (dateType == "hour")
                {
                    Dictionary<string, object> dic;
                    DateTime dtStart = DateTime.Parse(startTime);
                    DateTime dtEnd = dtStart.AddDays(1).AddSeconds(-1);
                    double?[] dl = new double?[24];
                    double?[] si = new double?[24];
                    sm = new StationModel(sid, dtStart, dtEnd);
                    DataTable dt = sm.DtTotalHourDL;
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        var dlList = dt.AsEnumerable();
                        for (int i = 0; i < 24; i++)
                        {
                            if (DateTime.Now < new DateTime(dtStart.Year, dtStart.Month, dtStart.Day, i, 0, 0))
                            {
                                dl[i] = null;
                                continue;
                            }
                            string year = dtStart.Year.ToString(), month = dtStart.Month.ToString(), day = dtStart.Day.ToString();
                            var current = dlList.Where(p => p["年"].ToString().Equals(year) && p["月"].ToString().Equals(month) && p["日"].ToString() == day && p["小时"].ToString() == i.ToString());
                            if (current != null && current.Count() > 0)
                            {
                                var data = current.Select(t => Convert.ToDouble(t["合计"])).ToList();
                                dl[i] = Math.Round(data[0], 2);
                            }
                            else
                            {
                                dl[i] = 0;
                            }
                        }
                    }

                    //TODO 辐照度一天24小时每小时的值
                    for (int i = 0; i < 24; i++)
                    {
                        if (dtStart.ToString("yyyy-MM-dd HH:00:00").Equals(DateTime.Now.ToString("yyyy-MM-dd HH:00:00")))
                        {
                            continue;
                        }
                        //sm = new StationModel(sid, dtStart, dtStart.AddHours(1).AddSeconds(-1));
                        //dl[i] = sm.DL;
                        sm = new StationModel(sid, dtStart, dtStart.AddHours(1).AddSeconds(-1));
                        si[i] = sm.AvgIrradiance;
                        dtStart = dtStart.AddHours(1);
                    }
                    dic = new Dictionary<string, object>();
                    dic.Add("name", "分时发电量");
                    dic.Add("data", dl);
                    dic.Add("type", "column");
                    Hashtable ht = new Hashtable();
                    ht.Add("valueSuffix", "kWh");
                    dic.Add("tooltip", ht);
                    list.Add(dic);
                    dic = new Dictionary<string, object>();
                    dic.Add("name", "辐照度");
                    dic.Add("yAxis", 1);
                    dic.Add("data", si);
                    dic.Add("type", "spline");
                    ht = new Hashtable();
                    ht.Add("valueSuffix", "W/㎡");
                    dic.Add("tooltip", ht);
                    list.Add(dic);
                }
                else if (dateType == "day")
                {
                    string start = startTime + "/01";
                    Dictionary<string, object> dic = new Dictionary<string, object>();
                    DateTime dtStart = DateTime.Parse(start);
                    DateTime dtEnd = dtStart.AddMonths(1).AddDays(-1);
                    int length = dtEnd.Day;
                    sm = new StationModel(sid, dtStart, dtEnd);
                    DataTable dt = sm.DtTotalDayDL;
                    double?[] dou = new double?[length];
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        string year = dtStart.Year.ToString(), month = dtStart.Month.ToString();
                        var dtList = dt.AsEnumerable();
                        for (int i = 0; i < length; i++)
                        {
                            if (DateTime.Now < new DateTime(dtStart.Year, dtStart.Month, (i + 1), 0, 0, 0))
                            {
                                dou[i] = null;
                                continue;
                            }
                            var current = dtList.Where(p => p["年"].ToString().Equals(year) && p["月"].ToString().Equals(month) && p["日"].ToString() == (i + 1).ToString());
                            if (current != null && current.Count() > 0)
                            {
                                var data = current.Select(t => Convert.ToDouble(t["合计"])).ToList();
                                dou[i] = Math.Round(data[0], 2);
                            }
                            else
                            {
                                dou[i] = 0;
                            }
                            //dtStart = dtStart.AddDays(1);
                        }
                    }
                    dic.Add("name", stationName);
                    dic.Add("data", dou);
                    dic.Add("type", "column");
                    list.Add(dic);
                }
                else if (dateType == "month")
                {
                    int year = int.Parse(startTime);
                    Dictionary<string, object> dic = new Dictionary<string, object>();
                    double?[] dou = new double?[12];
                    DateTime dtStart = new DateTime(year, 1, 1, 0, 0, 0);
                    DateTime dtEnd = dtStart.AddYears(1).AddSeconds(-1);
                    sm = new StationModel(sid, dtStart, dtEnd);
                    DataTable dt = sm.DtTotalMonthDL;
                    var dlList = dt.AsEnumerable();
                    string yearStr = dtStart.Year.ToString();
                    for (int i = 0; i < 12; i++)
                    {
                        if (DateTime.Now < new DateTime(dtStart.Year, (i + 1), 1, 0, 0, 0))
                        {
                            dou[i] = null;
                            continue;
                        }
                        var current = dlList.Where(p => p["年"].ToString().Equals(yearStr) && p["月"].ToString() == (i + 1).ToString());
                        if (current != null && current.Count() > 0)
                        {
                            dou[i] = Math.Round(current.Select(t => Convert.ToDouble(t["合计"])).ToList()[0], 2);
                        }
                        else
                        {
                            dou[i] = 0;
                        }
                    }
                    dic.Add("name", stationName);
                    dic.Add("data", dou);
                    dic.Add("type", "column");
                    list.Add(dic);
                }
                else
                {
                    int startYear = int.Parse(startTime);
                    int endYear = int.Parse(endTime);
                    DateTime startDate = new DateTime(startYear, 1, 1);
                    DateTime endDate = new DateTime(endYear, 1, 1).AddYears(1).AddSeconds(-1);
                    Dictionary<string, object> dic = new Dictionary<string, object>();
                    double[] dou = new double[endYear - startYear + 1];
                    sm = new StationModel(sid, startDate, endDate);
                    DataTable dt = sm.DtTotalYearDL;
                    var dlList = dt.AsEnumerable();
                    for (int i = 0; i <= endYear - startYear; i++)
                    {
                        var current = dlList.Where(p => p["年"].ToString().Equals((i + startYear).ToString()));
                        if (current != null && current.Count() > 0)
                        {
                            dou[i] = Math.Round(current.Select(t => Convert.ToDouble(t["合计"])).ToList()[0], 2);
                        }
                    }
                    dic.Add("name", stationName);
                    dic.Add("data", dou);
                    dic.Add("type", "column");
                    list.Add(dic);
                }
            }
            object obj = new { list = list };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetStationEnergys");
                sh.WriteLog("参数：startTime" + startTime);
                sh.WriteLog("参数：stationName" + stationName);
                sh.WriteLog("参数：sid" + sid);
                sh.WriteLog("参数：endTime" + endTime);
                sh.WriteLog("参数：dateType" + dateType);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 故障统计

        #endregion

        #region 故障查询

        #endregion

        #endregion

        #region Tree

        #region 省、市、电站
        [HttpPost]
        public HttpResponseMessage GetTreeOrg()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string userid = request.Form["userId"];
            try
            {
                OrgModel om = new OrgModel(userid);

                DataTable dtCity = new DataTable();
                DataTable dtAllOrg = new DataTable();
                DataTable dtUserAuthorization = new DataTable();
                DataTable dtCityId = new DataTable();

                dtCity = om.DtCity;                             //组织机构
                dtAllOrg = om.DtUserStation;                    //用户与电站关系
                dtUserAuthorization = om.DtAllOrgInfo;          //所有电站

                string strStationId = "";
                for (int i = 0; i < dtAllOrg.Rows.Count; i++)
                {
                    strStationId += "'" + dtAllOrg.Rows[i]["T_ORGID"] + "',";
                }
                strStationId = strStationId.Substring(0, strStationId.Length - 1);      //电站ID

                StationModel sm = new StationModel(strStationId);
                dtCityId = sm.DtCity;
                string strCityID = "";
                DataRow[] drStation = dtUserAuthorization.Select("T_ORGID in (" + strStationId + ")");  //电站            
                foreach (DataRow dr in drStation)
                {
                    //strCityID += "'" + dr["T_PARENTID"] + "',";
                    tree += "{id:'" + dr["T_ORGID"] + "',pId:'" + dr["T_CITYID"] + "',nodeID:'" + dr["T_ORGID"] + "',name:'" + dr["T_PLANTDESC"] + "',t:'" + dr["T_PLANTDESC"] + "',grade:'3',LONG:'" + dr["D_LONG"] + "',LAT:'" + dr["D_LAT"] + "'},";
                }

                for (int i = 0; i < dtCityId.Rows.Count; i++)
                {
                    strCityID += "'" + dtCityId.Rows[i][0] + "',";
                }
                strCityID = "(" + strCityID.Substring(0, strCityID.Length - 1) + ")";               //市ID
                DataRow[] drCity = dtCity.Select("T_CITYID in " + strCityID);                       //市

                string strPrivinceID = "";
                string sprivince = "";
                foreach (DataRow dr in drCity)
                {
                    strPrivinceID += "'" + dr["T_PARENTID"] + "',";
                    tree += "{id:'" + dr["T_CITYID"] + "',pId:'" + dr["T_PARENTID"] + "',nodeID:'" + dr["T_CITYID"] + "',name:'" + dr["T_CITYDESC"] + "',t:'" + dr["T_CITYDESC"] + "',grade:'2'},";
                }

                strPrivinceID = "(" + strPrivinceID.Substring(0, strPrivinceID.Length - 1) + ")";   //省ID
                DataRow[] drPrivince = dtCity.Select("T_CITYID in " + strPrivinceID);

                foreach (DataRow dr in drPrivince)
                {
                    tree += "{id:'" + dr["T_CITYID"] + "',pId:'" + dr["T_PARENTID"] + "',nodeID:'" + dr["T_CITYID"] + "',name:'" + dr["T_CITYDESC"] + "',t:'" + dr["T_CITYDESC"] + "',grade:'1'},";
                    sprivince = dr["T_PARENTID"].ToString();
                }

                drPrivince = dtCity.Select("T_CITYID ='" + sprivince + "'");
                if (drPrivince != null)
                    tree += "{id:'" + drPrivince[0]["T_CITYID"] + "',pId:'" + drPrivince[0]["T_PARENTID"] + "',nodeID:'" + drPrivince[0]["T_CITYID"] + "',name:'" + drPrivince[0]["T_CITYDESC"] + "',t:'" + drPrivince[0]["T_CITYDESC"] + "',grade:'0'},";

                if (tree != "")
                    tree = "[" + tree.Substring(0, tree.Length - 1) + "]";
                object obj = new
                {
                    tree = tree
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用时间：" + DateTime.Now);
                sh.WriteLog("调用方法名称：GetTreeOrg");
                sh.WriteLog("获取到参数：uid=" + userid);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion



        #endregion

        #region List 转换
        public IList<Hashtable> DataTableToList(DataTable dt)
        {
            IList<Hashtable> list = null;
            if (dt != null && dt.Rows.Count > 0)
            {
                list = new List<Hashtable>();
                Hashtable ht = null;
                foreach (DataRow row in dt.Rows)
                {
                    ht = new Hashtable();
                    foreach (DataColumn col in dt.Columns)
                    {
                        if (row[col.ColumnName] != null && !string.IsNullOrEmpty(Convert.ToString(row[col.ColumnName])))
                        {
                            ht.Add(col.ColumnName.ToUpper(), row[col.ColumnName]);
                        }
                        else
                        {
                            ht.Add(col.ColumnName.ToUpper(), "");
                        }
                    }
                    list.Add(ht);
                }
            }
            return list;
        }
        #endregion

    }
}